<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/8/21 0021
 * Time: 10:14
 */

namespace app\currency\service;


use Endroid\QrCode\QrCode;
use library\File;
use library\tools\Data;
use think\Db;
use think\Exception;

class MemberService
{
    /**
     * @param string $openid openid
     * @param int $pid pid
     * @return array|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function set($openid = '',$pid = 0){
        // 用户信息
        $user = Db::name('Member')->where('openid',$openid)->find();
        // 如果用户不存在，创建用户
        if(!$user){
            Db::name('Member')->insert(['openid' => $openid,'pid' => $pid]);
            $user = Db::name('Member')->where('openid','eq',$openid)->find();
        }
        return $user;
    }
    public static function bind($phone,$pid = 0){
        $mid = Db::name('Member')->where('phone',$phone)->value('id');
        if(!$mid){
            $mid = Db::name('Member')->insertGetId(['phone' => $phone,'pid' => $pid]);
        }
        return $mid;
    }
    /**
     * 积分变动记录
     * @param int $mid 用户ID
     * @param int $amount 积分变动数量
     * @param string $desc 积分变动说明
     * @return int|string
     */
    public static function setIntegralLog($mid,$amount,$desc='')
    {
        return Db::name('MemberIntegralLog')->insert([
           'mid' => $mid,
           'amount' => $amount,
           'desc' => $desc
        ]);
    }

    /**
     * 余额变动记录
     * @param int $mid 用户ID
     * @param int $amount 余额变动数量
     * @param string $desc 余额变动说明
     * @return int|string
     */
    public static function setBalanceLog($mid,$amount,$desc='')
    {
        return Db::name('MemberBalanceLog')->insert([
            'mid' => $mid,
            'amount' => $amount,
            'desc' => $desc
        ]);
    }

    /**
     * 生成唯一邀请码
     * @param int $length 邀请码长度
     * @return string 邀请码
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function create_invite_code($length = 10)
    {
        $code = Data::randomCode($length, 3);
        $r = true;
        while($r) {
            //$r = false;
            $r = Db::name('Member')->where("invite_code", $code)->find();
            if ($r) {
                $code = Data::randomCode($length, 3);
            }
        }
        return $code;
    }

    /**
     * 生成用户token
     * @param $mid
     * @return string
     */
    public static function userToken($mid)
    {
        //生成$token
        $token = getGuid();
        //缓存3rd_session
        cache($token, ['id' => $mid, 'time' => time()], 3600 * 24 * 30);
        return $token;
    }
    /**
     * 获取用户分享二维码地址
     * @param string $invite_code 邀请码
     * @return string
     * @throws \Endroid\QrCode\Exceptions\ImageFunctionFailedException
     * @throws \Endroid\QrCode\Exceptions\ImageFunctionUnknownException
     * @throws \Endroid\QrCode\Exceptions\ImageTypeInvalidException
     * @throws \think\Exception
     */
    public static function _getUserQrCode($invite_code)
    {
        $qr_code_name = "qrcode/{$invite_code}.jpeg";
        $file = File::instance('local');
        //如果二维码不存在
        if( !$file->has($qr_code_name) ) {
            $uri = url("currency/index/register",['invite_code' => $invite_code],true,true);
            $qrCode = new QrCode();
            $qrCode
                ->setText($uri)
                ->setSize(300)
                ->setPadding(10)
                ->setErrorCorrection('high')
                ->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0])
                ->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0])
                //->setLabel('Scan the code')
                ->setLabelFontSize(16)
                ->setImageType(QrCode::IMAGE_TYPE_PNG);
            //二维码保存到本地
            $info = $file->save($qr_code_name, $qrCode->get());
            //保存失败
            if (!is_array($info) || !isset($info['url'])) {
                throw new Exception('用户二维码生成失败！');
            }
        }
        return $file->path($qr_code_name);
    }
}